package edu.whu.tao.util;

import java.util.Properties;

import org.springframework.beans.factory.FactoryBean;

import edu.whu.tao.constant.CommonConstants;

/**
 * 
 * <P>c3p0数据库连接池用户名和密码加密解密工具</P>
 * @author 陶焕(13294175866)
 * @date 2016年4月17日 下午8:20:59
 */
public class PropertiesEncryptFactoryBean implements FactoryBean {
	
	private Properties properties;

	public Object getObject() throws Exception {
		return getProperties();
	}

	public Class getObjectType() {
		return Properties.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public Properties getProperties() {
		return this.properties;
	}

	public void setProperties(Properties inProperties) {
		this.properties = inProperties;
		String originalUsername = this.properties.getProperty(CommonConstants.DB_USER_KEY);
		String originalPassword = this.properties.getProperty(CommonConstants.DB_PWD_KEY);
		if (originalUsername != null) {
			String newUsername = deEncryptUsername(originalUsername);
			this.properties.put(CommonConstants.DB_USER_KEY, newUsername);
		}
		if (originalPassword != null) {
			String newPassword = deEncryptPassword(originalPassword);
			this.properties.put(CommonConstants.DB_PWD_KEY, newPassword);
		}
	}

	private String deEncryptUsername(String originalUsername) {
		return AESUtils.getInstance().decrypt(originalUsername);
	}

	private String deEncryptPassword(String originalPassword) {
		return AESUtils.getInstance().decrypt(originalPassword);
	}
}
